import {defineStore} from "pinia";
import {refreshToken, TOKEN_KEY, USER_KEY} from "@/api/_const.js";
import {login, logoutApi} from "@/api/auth.js";
import {getCurrentUser} from "@/api/user.js";
import {ElMessage} from "element-plus";

export const useAuthStore = defineStore('auth', {
    state: () => ({
        user: JSON.parse(localStorage.getItem(USER_KEY) || 'null'),
        token: localStorage.getItem(TOKEN_KEY) || null,
        refreshToken: localStorage.getItem(refreshToken) || null,
        isAuthenticated: !!localStorage.getItem(TOKEN_KEY)
    }),

    actions: {
        async fetchLogin(credentials) {
            try {
                const response = await login(credentials);
                if (response.code !== 200) {
                    return Promise.resolve(response);
                }
                this.token = response.data.accessToken;
                this.refreshToken = response.data.refreshToken;
                this.isAuthenticated = true;

                // 保存到 localStorage
                localStorage.setItem(TOKEN_KEY, this.token);
                let fetchUserRes = await this.fetchUser();
                if (fetchUserRes.code !== 200) {
                    ElMessage.error(fetchUserRes.message);
                }
                return Promise.resolve(response);
            } catch (error) {
                return Promise.reject(error);
            }
        },

        async fetchUser() {
            try {
                const response = await getCurrentUser();
                this.user = response.data;
                localStorage.setItem(USER_KEY, JSON.stringify(this.user)); // 保存用户信息
                return Promise.resolve(response);
            } catch (error) {
                return Promise.reject(error);
            }
        },

        async logout() {
            try {
                const res = await logoutApi();
                this.reset();
                return Promise.resolve(res);
            } catch (error) {
                return Promise.reject(error);
            }
        },

        reset() {
            this.user = null;
            this.token = null;
            this.isAuthenticated = false;
            // 清除 localStorage
            localStorage.removeItem(TOKEN_KEY);
            localStorage.removeItem(USER_KEY);
        }
    }
});